import axios from "axios";
import { ElMessage } from "element-plus";
import router from "@/router";

const instance = axios.create({
    baseURL: import.meta.env.VITE_API_BASE_URL || '/api', // 生产环境使用环境变量,
    timeout: 50000,
});

// 请求拦截器：自动添加 Token
instance.interceptors.request.use(
    (config) => {
        const token = localStorage.getItem("token");
        if (token) {
            config.headers.Authorization = `Bearer ${token}`;
        }
        return config;
    },
    (error) => {
        return Promise.reject(error);
    }
);

// 响应拦截器：自动处理未授权
instance.interceptors.response.use(
    (response) => response,
    (error) => {
        if (error.response?.status === 401) {
            ElMessage.error("未授权，请重新登录");
            localStorage.removeItem("token");
            router.push("/login");
        } else {
            ElMessage.error(error.response?.data?.message || "请求失败");
        }
        return Promise.reject(error);
    }
);

export default instance;
